package org.smi.concurrent;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;  
  
public class ConcurrentMethodCallExample {  
  
    public static void main(String[] args) throws ExecutionException, InterruptedException {  
        // 创建三个CompletableFuture对象，分别用于调用三个方法  
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(ConcurrentMethodCallExample::method1);  
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(ConcurrentMethodCallExample::method2);  
        CompletableFuture<String> future3 = CompletableFuture.supplyAsync(ConcurrentMethodCallExample::method3);  
  
        // 使用thenCombine或thenAccept等方法来处理每个方法的返回结果  
        // 这里我们使用CompletableFuture.allOf等待所有任务完成，然后获取结果  
        CompletableFuture.allOf(future1, future2, future3).join();  
  
        // 获取每个方法的返回结果  
        String result1 = future1.get();  
        String result2 = future2.get();  
        String result3 = future3.get();  
  
        // 打印结果  
        System.out.println("Result from method1: " + result1);  
        System.out.println("Result from method2: " + result2);  
        System.out.println("Result from method3: " + result3);  
    }  
  
    public static String method1() {  
        // 模拟长时间运行的任务  
        try {
            System.out.println("开始1");
            Thread.sleep(1000);
            System.out.println("结束1");
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        }  
        return "Result from method1";  
    }  
  
    public static String method2() {  
        // 模拟长时间运行的任务  
        try {
            System.out.println("开始2");
            Thread.sleep(2500);
            System.out.println("结束2");
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        }  
        return "Result from method2";  
    }  
  
    public static String method3() {  
        // 模拟长时间运行的任务  
        try {
            System.out.println("开始3");
            Thread.sleep(5000);

            System.out.println("结束3");
        } catch (InterruptedException e) {  
            e.printStackTrace();  
        }  
        return "Result from method3";  
    }  
}